//
//  testViewController.m
//  ZJControlsClass
//
//  Created by wandoufo on 2024/12/23.
//

#import "testViewController.h"

@interface testViewController () <UIDocumentPickerDelegate>

@end

@implementation testViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // 创建上传按钮
    UIButton *uploadButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [uploadButton setTitle:@"上传文件" forState:UIControlStateNormal];
    [uploadButton setFrame:CGRectMake(20, 100, 200, 44)];
    [uploadButton addTarget:self action:@selector(uploadButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:uploadButton];
}

// 上传按钮点击事件处理
- (void)uploadButtonTapped:(UIButton *)sender {
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] 
        initWithDocumentTypes:@[@"public.data"] 
        inMode:UIDocumentPickerModeImport];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

// 文件选择完成后的处理
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    NSURL *selectedFileURL = urls.firstObject;
    // 获取文件数据
    NSData *fileData = [NSData dataWithContentsOfURL:selectedFileURL];
    
    // 创建请求体
    NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    
    NSMutableData *body = [NSMutableData data];
    
    // 添加文件数据
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", selectedFileURL.lastPathComponent] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:fileData];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 结束标记
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://test.sczhbf.com:58088/app-api/infra/file/uploadDetail"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"1" forHTTPHeaderField:@"Tenant-Id"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [request setValue:[defaults valueForKey:@"accessToken"] forHTTPHeaderField:@"Authorization"];
    [request setHTTPBody:body];
    
    // 发起上传请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"上传失败:%@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"上传失败"];
            });
            return;
        }
        
        NSError *jsonError;
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
        
        if (jsonError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"解析响应失败"];
            });
            return;
        }
        
        if ([responseDict[@"code"] intValue] == 200) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showSuccess:@"上传成功"];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:responseDict[@"msg"] ?: @"上传失败"];
            });
        }
    }];
    [task resume];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
